package mclight.text;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import mclight.Component;
import mclight.containers.Container;
import mclight.Style;

class InputText extends Component
{	
	public function new(
		?parent:DisplayObjectContainer, ?container:Container, xpos:Float = 0, ypos:Float = 0,
		text:String = "", defaultHandler:Event->Dynamic = null
	)
	{
		_password = false;
		_text = text;
		super(parent, container, xpos, ypos);
		if(defaultHandler != null)
		{
			//addEventListener(Event.CHANGE, defaultHandler);
		}
	}
	
	override function init()
	{
		super.init();
		setSize(100, 18);
	}
	
	var _back:Sprite;
	
	var _tf:TextField;
	
	override function construct()
	{
		_back = new Sprite();
		_back.filters = [getComponentShadow(2, true)];
		_sprite.addChild(_back);
		
		_tf = new TextField();
		_tf.selectable = true;
		_tf.type = TextFieldType.INPUT;
		_tf.defaultTextFormat = Style.INPUT_TEXT_FORMAT;
		_sprite.addChild(_tf);
		_tf.addEventListener(Event.CHANGE, onChange);
		
	}
	
	// PUBLIC METHODS
	
	public override function draw()
	{
		super.draw();
		_back.graphics.clear();
		_back.graphics.beginFill(Style.BACKGROUND);
		_back.graphics.drawRect(0, 0, _width, _height);
		_back.graphics.endFill();
		
		_tf.displayAsPassword = _password;
		
		_tf.text = _text;
		_tf.width = _width - 4;
		if(_tf.text == "")
		{
			_tf.text = "X";
			_tf.height = Math.min(_tf.textHeight + 4, _height);
			_tf.text = "";
		}
		else
		{
			_tf.height = Math.min(_tf.textHeight + 4, _height);
		}
		_tf.x = 2;
		_tf.y = Math.round(_height / 2 - _tf.height / 2);
	}
	
	// HANDLERS
	
	function onChange(event:Event)
	{
		_text = _tf.text;
		//dispatchEvent(new Event(Event.CHANGE));
	}
	
	// PROPERTIES
	
	public var text(getText, setText):String;
	var _text:String;
	function setText(t:String)
	{
		_text = t;
		invalidate();
		return t;
	}
	function getText()
	{
		return _text;
	}
	
	public var restrict(getRestrict, setRestrict):String;
	function setRestrict(str:String)
	{
		_tf.restrict = str;
		return str;
	}
	function getRestrict()
	{
		return _tf.restrict;
	}
	
	public var maxChars(getMaxChars, setMaxChars):Int;
	function setMaxChars(max:Int)
	{
		_tf.maxChars = max;
		return max;
	}
	function getMaxChars()
	{
		return _tf.maxChars;
	}
	
	public var password(getPassword, setPassword):Bool;
	var _password:Bool;
	function setPassword(b:Bool)
	{
		_password = b;
		invalidate();
		return b;
	}
	function getPassword()
	{
		return _password;
	}
}
